package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zuipin.entity.MemberLevel;
import com.zuipin.entity.RocketMqInfo;
import com.zuipin.entity.SysUser;
import com.zuipin.entity.product.CategoryInfo;
import com.zuipin.entity.product.ProductDetail;
import com.zuipin.entity.product.ProductExtInfo;
import com.zuipin.entity.product.ProductImg;
import com.zuipin.entity.product.ProductInfo;
import com.zuipin.entity.product.ProductPrice;
import com.zuipin.entity.product.ProductPropertyValue;
import com.zuipin.entity.shoppingCart.CartProInfo;
import com.zuipin.enums.BusinessType;
import com.zuipin.enums.ProductStatus;
import com.zuipin.enums.ProductType;
import com.zuipin.enums.ProductUnit;
import com.zuipin.enums.RocketMQTagEnum;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.ProductInfoMapper;
import com.zuipin.mapper.PropertiesInfoMapper;
import com.zuipin.service.IBaseProductBrandService;
import com.zuipin.service.ICategoryInfoService;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.IMemberLevelService;
import com.zuipin.service.IProductDetailService;
import com.zuipin.service.IProductExtInfoService;
import com.zuipin.service.IProductImgService;
import com.zuipin.service.IProductInfoService;
import com.zuipin.service.IProductPriceService;
import com.zuipin.service.IProductPropertyValueService;
import com.zuipin.service.IPropertiesInfoService;
import com.zuipin.service.IRocketMQService;
import com.zuipin.service.IRuleSetService;
import com.zuipin.service.IShoppingCartService;
import com.zuipin.service.ISysUserService;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.CommonUtils;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.Convert;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.BackExtProDetailVo;
import com.zuipin.vo.BackProInfoPrice;
import com.zuipin.vo.BackProInfoPropertyVo;
import com.zuipin.vo.BackProductInfoDetailVo;
import com.zuipin.vo.BackProductInfoVo;
import com.zuipin.vo.BackProductPlatformSearchVo;
import com.zuipin.vo.CategoryInfoVo;
import com.zuipin.vo.HotReviewProVo;
import com.zuipin.vo.PriceTypeVo;
import com.zuipin.vo.ProExtDetailVo;
import com.zuipin.vo.ProExtInfoVo;
import com.zuipin.vo.ProExtSerachVo;
import com.zuipin.vo.ProExtVo;
import com.zuipin.vo.ProPriceVo;
import com.zuipin.vo.ProSearchVo;
import com.zuipin.vo.ProVo;
import com.zuipin.vo.ProductAmountVo;
import com.zuipin.vo.ProductBrandVo;
import com.zuipin.vo.ProductCashierVo;
import com.zuipin.vo.ProductFromCbsVo;
import com.zuipin.vo.ProductInfoVo;
import com.zuipin.vo.ProductPriceVo;
import com.zuipin.vo.ProductPropertyValueVo;
import com.zuipin.vo.ProductSearchVo;
import com.zuipin.vo.PropValVo;
import com.zuipin.vo.SearchProductInfoVo;
import com.zuipin.vo.SpecialPriceVo;

import net.sf.json.JSONObject;

/**
 * 商品信息业务类实现
 *
 * @ClassName ProductInfoServiceImpl
 * @author wangcongyi
 * @date 2017年4月19日 下午7:08:04
 */
@Service
public class ProductInfoServiceImpl implements IProductInfoService {
	
	@Resource
	private ProductInfoMapper				productInfoMapper;
	@Resource
	private IProductExtInfoService			productExtInfoService;
	@Resource
	private IProductDetailService			productDetailService;
	// @Resource
	// private ProductImgMapper productImgMapper;
	@Resource
	private IProductImgService				productImgService;
	@Resource
	private PropertiesInfoMapper			propertiesInfoMapper;
	@Resource
	private IPropertiesInfoService			propertiesInfoService;
	@Resource
	private IProductPriceService			productPriceService;
	@Resource
	private IProductPropertyValueService	productPropertyValueService;
	@Resource
	private IShoppingCartService			shoppingCartService;
	@Resource
	private IMemberLevelService				memberAccountService;
	@Resource
	private IIntegralRecordService			integralRecordService;
	@Resource
	private IRuleSetService					ruleSetService;
	@Resource
	private IRocketMQService				rocketMQService;
	@Resource
	private ICategoryInfoService			categoryInfoService;
	@Resource
	private IBaseProductBrandService		baseProductBrandService;
	@Resource
	private ISysUserService					sysUserService;
	
	@Value("${imgpath.zpDomain}")
	private String							zpDomain;					// 图片拼接域名
	
	@Value("${imgpath.zpThumbnail230x184}")
	private String							zpThumbnail230x184;			// 缩略图拼接路径规格230X184
	
	@Value("${imgpath.zpThumbnail78x65}")
	private String							zpThumbnail78x65;			// 缩略图拼接路径规格78x65
	
	@Value("${imgpath.zpRawImage}")
	private String							zpRawImage;					// 原图拼接路径
	
	@Override
	public int deleteByPrimaryKey(Long id) {
		// TODO Auto-generated method stub
		return productInfoMapper.deleteByPrimaryKey(id);
	}
	
	@Override
	public int insert(ProductInfo record) {
		// TODO Auto-generated method stub
		return productInfoMapper.insert(record);
	}
	
	@Override
	public boolean insertSelective(ProductInfo record) {
		// TODO Auto-generated method stub
		return productInfoMapper.insertSelective(record);
	}
	
	@Override
	public ProductInfo findProById(Long id) {
		// TODO Auto-generated method stub
		return productInfoMapper.findProById(id);
	}
	
	@Override
	public HotReviewProVo getHotReviewProVo(String proSku) {
		// TODO Auto-generated method stub
		return productInfoMapper.getHotReviewProVo(proSku);
	}
	
	@Override
	public HotReviewProVo getHotReviewProVo(Long id) {
		// TODO Auto-generated method stub
		return productInfoMapper.getHotReviewProVoById(id);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean insertXpPro(ProductInfo productInfo, ProPriceVo price) {
		// 获取当前时间
		String currentTime = DateUtils.getCurrentDateTime();
		boolean flag = false;
		// 获取原商品 商品ID和系统ID
		Long proId = productInfo.getId();
		Long sysId = productInfo.getSysId();
		JSONObject params = new JSONObject();
		params.put("proId", proId);
		params.put("sysId", sysId);
		productInfo.setCreateTime(currentTime);
		productInfo.setUpdateTime(currentTime);
		// 执行添加商品信息
		flag = productInfoMapper.insertSelective(productInfo);
		if (flag) {
			// 获取体验品商品信息ID
			proId = productInfo.getId();
			// 获取体验品商品信息SKU
			String proSku = productInfo.getProSku();
			ProductExtInfo pExtInfo = productExtInfoService.selectByProId(params);
			params.put("proExtId", pExtInfo.getId());
			pExtInfo.setId(null);
			pExtInfo.setCreateTime(currentTime);
			pExtInfo.setUpdateTime(currentTime);
			pExtInfo.setProId(proId);
			pExtInfo.setProSku(proSku);
			pExtInfo.setState("OFF_SHELF");
			// 执行添加商品拓展信息
			flag = productExtInfoService.insertSelective(pExtInfo);
			Long proExtId = null;
			if (flag) {
				proExtId = pExtInfo.getId();
				List<ProductDetail> details = productDetailService.findByProExtId(params);
				if (details != null && !details.isEmpty()) {
					for (ProductDetail productDetail : details) {
						productDetail.setCreateTime(currentTime);
						productDetail.setUpdateTime(currentTime);
						productDetail.setProExtId(proExtId);
					}
				}
				// 执行添加商品详情信息列表
				productDetailService.insertBatch(details);
			}
			// 执行批量添加商品属性 属性值列表信息
			List<ProductPropertyValue> productPropertyValues = productPropertyValueService.selectByProId(params);
			if (productPropertyValues != null && !productPropertyValues.isEmpty()) {
				for (ProductPropertyValue productPropertyValue : productPropertyValues) {
					productPropertyValue.setCreateTime(currentTime);
					productPropertyValue.setUpdateTime(currentTime);
					productPropertyValue.setProId(proId);
				}
				productPropertyValueService.insertBatch(productPropertyValues);
			}
			// 执行批量添加体验品图片信息列表
			List<ProductImg> productImgs = productImgService.getByProExtId(params);
			if (productImgs != null && !productImgs.isEmpty()) {
				for (ProductImg productImg : productImgs) {
					productImg.setCreateTime(currentTime);
					productImg.setUpdateTime(currentTime);
					productImg.setProExtId(proExtId);
				}
				productImgService.insertBatch(productImgs);
			}
			// 执行 删除原有的价格列表 添加新价格列表
			params.put("proId", proId); // 插入体验品ID
			List<ProductPrice> prices = price.getProductPrices();
			if (prices != null && !prices.isEmpty()) {
				for (ProductPrice productPrice : prices) {
					productPrice.setProId(proId);
					productPrice.setCreateTime(currentTime);
					productPrice.setUpdateTime(currentTime);
				}
				productPriceService.deleteByProId(params);
				productPriceService.insertBatch(prices);
			}
		}
		return flag;
	}
	
	@Override
	public ProductInfo selectById(Long id) {
		// TODO Auto-generated method stub
		return productInfoMapper.selectById(id);
	}
	
	@Override
	public ProductInfo findProductInfoById(Long id) {
		// TODO Auto-generated method stub
		return productInfoMapper.findProductInfoById(id);
	}
	
	@Override
	public boolean updateByPrimaryKeySelective(ProductInfo record) {
		// TODO Auto-generated method stub
		return productInfoMapper.updateByPrimaryKeySelective(record);
	}
	
	@Override
	public List<Long> findIdByName(String proName) {
		// TODO Auto-generated method stub
		return productInfoMapper.findIdByName(proName);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updatePro(ProductInfo productInfo, ProductPropertyValueVo prop) {
		// TODO Auto-generated method stub
		// 获取当前时间
		String currentTime = DateUtils.getCurrentDateTime();
		productInfo.setUpdateTime(currentTime);
		boolean flag = false;
		flag = productInfoMapper.updateByPrimaryKeySelective(productInfo);
		List<ProductPropertyValue> props = prop.getProductPropertyValues();
		if (flag && props != null && !props.isEmpty()) {
			for (ProductPropertyValue productPropertyValue : props) {
				productPropertyValue.setUpdateTime(DateUtils.getCurrentDateTime());
			}
			productPropertyValueService.updateBatch(props);
		}
		return flag;
	}
	
	@Override
	public int updateByPrimaryKey(ProductInfo record) {
		// TODO Auto-generated method stub
		return productInfoMapper.updateByPrimaryKey(record);
	}
	
	@Override
	public ProductInfoVo getProExtInfo(JSONObject object, boolean isLogin) {
		// TODO Auto-generated method stub
		ProductInfoVo vo = new ProductInfoVo();
		ProductInfo productInfo = selectByProSku(object.getString("productSku"));
		vo.setProductInfo(productInfo);
		ProductExtInfo productExtInfo = productExtInfoService.selectByProSku(object);
		vo.setProductExtInfo(productExtInfo);
		if (productExtInfo != null) {
			// 拼接图片地址
			String thumbnailPath = zpDomain + zpThumbnail78x65;
			String rawPath = zpDomain + zpRawImage;
			object.put("proExtId", productExtInfo.getId());
			object.put("thumbnailPath", thumbnailPath);
			object.put("rawPath", rawPath);
			vo.setProductImgList(productImgService.selectByProExtId(object));
			productExtInfo.setIsAgents(ProductExtInfo.NO_AGENTS); // 默认设置不是代理商
		} else {
			// 商品拓展信息为NULL的情况下直接返回NULL
			return null;
		}
		// 查询特价规则
		List<String> skus = new ArrayList<>();
		skus.add(productExtInfo.getProSku());
		List<SpecialPriceVo> specialPriceVos = ruleSetService.findSpecialPriceBySkus(skus, productExtInfo.getSysId(), null, object.getString("device"));
		if (null != specialPriceVos && !specialPriceVos.isEmpty()) {
			SpecialPriceVo specialPriceVo = specialPriceVos.get(0);
			productExtInfo.setIsSales(ProductExtInfo.IS_SPECIAL);
			productExtInfo.setSalesPrice(specialPriceVo.getPrice());
			productExtInfo.setSalesStartTime(specialPriceVo.getStartTime());
			productExtInfo.setSalesEndTime(specialPriceVo.getEndTime());
		} else {
			productExtInfo.setIsSales(ProductExtInfo.NO_SPECIAL);
		}
		if (productInfo != null) {
			object.put("proId", productInfo.getId());
			List<ProductPrice> prices = productPriceService.selectByProId(object);
			if (isLogin && prices != null && !prices.isEmpty()) {
				// 登陆的情况下要通过会员ID查询会员等级计算出会员价/代理商价
				PriceTypeVo priceTypeVo = productPriceService.getMemberPrice(object.getLong("memberId"), object.getLong("sysId"), prices.get(0).getPrice(), productInfo.getId());
				if (priceTypeVo != null) {
					ProductPrice productPrice = new ProductPrice(ProductPrice.MEMBERNO, priceTypeVo.getPrice());
					prices.add(productPrice);
					// 判断是否代理商
					if (priceTypeVo.isAgents()) {
						productExtInfo.setIsAgents(ProductExtInfo.YES_AGENTS);
					}
				}
				
			}
			vo.setProductPrice(prices);
		}
		
		return vo;
	}
	
	@Override
	public ProductInfo selectByProSku(String proSku) {
		// TODO Auto-generated method stub
		return productInfoMapper.selectByProSku(proSku);
	}
	
	@Override
	public List<ProExtVo> seachProduct(ProSearchVo pro, Pagination page) {
		return null;
		// TODO Auto-generated method stub
		// return productInfoMapper.seachProduct(pro, page);
	}
	
	@Override
	public List<ProExtVo> seachProduct(ProSearchVo pro, JSONObject obj) {
		// TODO Auto-generated method stub
		// 拼接图片路径
		String imgPath = zpDomain + zpThumbnail230x184;
		pro.setImgPath(imgPath);
		List<ProExtVo> list = productInfoMapper.seachProduct(pro, obj);
		
		// 如果是积分商品则填充积分价格信息 如果是特价则显示特价
		for (ProExtVo vo : list) {
			
			// 如果有特价
			if (vo.getIsSales().equals(ProExtVo.IS_SPECIAL)) {
				vo.setProPrice(vo.getSalesPrice());
			}
			
			if (vo.getIsExchangeIntegral().equals(ProductInfo.YES_EXCHANGE_INTEGRAL)) {
				ProductPrice p = productPriceService.findByType(vo.getProId(), pro.getSysId(), ProductPrice.INTEGRAL);
				if (p != null) {
					vo.setIntegralPrice(p.getPrice().intValue());
				}
			}
			
		}
		return list;
	}
	
	@Override
	public Integer getTotalRecord(ProSearchVo pro) {
		// TODO Auto-generated method stub
		return productInfoMapper.getTotalRecord(pro);
	}
	
	@Override
	public List<ProExtInfoVo> queryProExtInfo(ProExtSerachVo ProExt, boolean isLogin) {
		// TODO Auto-generated method stub
		// 拼接图片路径
		String imgPath = zpDomain + zpThumbnail78x65;
		ProExt.setImgPath(imgPath);
		List<ProExtInfoVo> proExtInfoVos = productInfoMapper.queryProExtInfo(ProExt);
		if (isLogin && proExtInfoVos != null && !proExtInfoVos.isEmpty()) {
			for (ProExtInfoVo vo : proExtInfoVos) {
				BigDecimal price = vo.getProPrice();
				PriceTypeVo priceTypeVo = null;
				vo.setIsAgents(ProductExtInfo.NO_AGENTS); // 默认设置为不是代理商
				if (price != null) {
					priceTypeVo = productPriceService.getMemberPrice(ProExt.getMemberId(), ProExt.getSysId(), price, vo.getProId());
					if (priceTypeVo != null) {
						vo.setMemberPrice(priceTypeVo.getPrice());
						// 判断是否代理商
						if (priceTypeVo.isAgents()) {
							vo.setIsAgents(ProductExtInfo.YES_AGENTS);
						}
					} else {
						break;
					}
				}
				
			}
		}
		return proExtInfoVos;
	}
	
	@Override
	public Map<String, ProExtInfoVo> queryProExtInfo(ProExtSerachVo ProExt) {
		// TODO Auto-generated method stub
		String imgPath = zpDomain + zpThumbnail78x65;
		ProExt.setImgPath(imgPath);
		List<ProExtInfoVo> list = productInfoMapper.queryProExtInfo(ProExt);
		Map<String, ProExtInfoVo> map = new HashMap<String, ProExtInfoVo>();
		for (ProExtInfoVo vo : list) {
			map.put(vo.getProSku(), vo);// 2017-8-25修改~~原先key是proNo
		}
		return map;
	}
	
	@Override
	public ProductInfo selectByProNo(String proNo) {
		// TODO Auto-generated method stub
		return productInfoMapper.selectByProNo(proNo);
	}
	
	@Override
	public ProExtDetailVo selectProForGeneral(JSONObject params) {
		// TODO Auto-generated method stub
		ProExtDetailVo vo = new ProExtDetailVo();
		ProductInfo productInfo = productInfoMapper.selectByProSku(params.getString("productSku"));
		vo.setProductInfo(productInfo);
		List<PropValVo> propValVos = null;
		if (null != productInfo) {
			params.put("catId", productInfo.getCatId());
			params.put("proId", productInfo.getId());
			propValVos = propertiesInfoService.selectPropValInfo(params);
			vo.setPropVals(propValVos);
		}
		return vo;
	}
	
	@Override
	public ProExtDetailVo selectProDetail(JSONObject params) throws CustomException {
		// TODO Auto-generated method stub
		ProExtDetailVo vo = new ProExtDetailVo();
		ProductInfo productInfo = productInfoMapper.selectByProductSku(params);
		if (productInfo != null) {
			if (ProductInfo.ENABLE != productInfo.getStatus()) {
				throw new CustomException(ErrorCode.PRODUCT_DISABLED.getCode(), "该商品已被冻结,不可创建");
			}
		}
		vo.setProductInfo(productInfo);
		List<PropValVo> propValVos = null;
		if (null != productInfo) {
			params.put("catId", productInfo.getCatId());
			params.put("proId", productInfo.getId());
			propValVos = propertiesInfoService.selectPropValInfo(params);
			vo.setPropVals(propValVos);
			ProductExtInfo productextinfo = productExtInfoService.selectByProSku(params);
			vo.setProductExtInfo(productextinfo);
			// 装载商品详情信息和图片相册列表
			// if (null != productextinfo) {
			// params.put("proExtId", productextinfo.getId());
			// vo.setProductDetails(productDetailService.findByProExtId(params));
			// vo.setProductImgs(productImgService.findByProExtId(params));
			// }
			vo.setProductPrices(productPriceService.findByProId(params));
		}
		return vo;
		
	}
	
	@Override
	public Map<String, Object> getByProSku(String proSku) {
		// TODO Auto-generated method stub
		return productInfoMapper.getByProSku(proSku);
	}
	
	@Override
	public boolean updateSalesByProSku(String proSku, BigDecimal salesNum) {
		// TODO Auto-generated method stub
		JSONObject params = new JSONObject();
		params.put("proSku", proSku);
		params.put("salesNum", salesNum);
		return productExtInfoService.updateSalesByProSku(params);
	}
	
	@Override
	public List<ProductInfo> checkPro(JSONObject params) {
		// TODO Auto-generated method stub
		return productInfoMapper.checkPro(params);
	}
	
	@Override
	public List<ProductInfo> findProduct(ProductSearchVo search, Pagination page) {
		// TODO Auto-generated method stub
		return productInfoMapper.findProduct(search, page);
	}
	
	@Override
	public ProductInfo isExists(JSONObject params) {
		// TODO Auto-generated method stub
		return productInfoMapper.isExists(params);
	}
	
	@Override
	public boolean modifyStatus(JSONObject params) {
		// TODO Auto-generated method stub
		return productInfoMapper.modifyStatus(params);
	}
	
	@Override
	public List<ProductInfo> findProductExt(ProductSearchVo search, Pagination page) {
		// TODO Auto-generated method stub
		return productInfoMapper.findProductExt(search, page);
	}
	
	@Override
	public List<ProductInfo> findProductByCatId(ProductSearchVo search, Pagination page) {
		// TODO Auto-generated method stub
		return productInfoMapper.findProductByCatId(search, page);
	}
	
	@Override
	public List<ProductInfo> findProductExtByCatId(ProductSearchVo search, Pagination page) {
		// TODO Auto-generated method stub
		return productInfoMapper.findProductExtByCatId(search, page);
	}
	
	@Override
	public Map<String, Map<String, Object>> getStock(String proSkus) throws CustomException {
		return shoppingCartService.findCisBranchStockByProSkus(proSkus);
	}
	
	@Override
	public Map<String, Map<String, Object>> queryProInfoType(List<String> skuList) {
		Map<String, Map<String, Object>> resultMap = new HashMap<String, Map<String, Object>>();
		List<Map<String, Object>> list = productInfoMapper.queryProInfoType(skuList);
		if (list != null) {
			for (Map<String, Object> proMap : list) {
				resultMap.put(Convert.toString(proMap.get("sku")), proMap);
			}
		}
		return resultMap;
	}
	
	/**
	 * 后台下单查询商品
	 *
	 * @Title: searchBySkuFromBack 
	 * @author: wuyicheng
	 * @date: 2017年8月7日下午2:11:57 
	 * @param memberId
	 * @param sysId
	 * @param proSku
	 * @param proNum
	 * @param device
	 * @return
	 * @throws CustomException
	 * @throws
	 */
	@Override
	public Result<ProductAmountVo> searchBySkuFromBack(Long memberId, Long sysId, String proSku, BigDecimal proNum, String device) throws CustomException {
		Result<ProductAmountVo> result = new Result<>(ErrorCode.SUCCESS);
		CartProInfo cartProInfo = shoppingCartService.getProInfo(null, proSku, sysId, memberId, device, proNum, false);
		if (CartProInfo.IS_ON_SHELVES_NO_0.equals(cartProInfo.getIsOnShelves())) {
			throw new CustomException(ErrorCode.ON_SHELF.getCode(), "该商品未上架");
		}
		ProductAmountVo productAmountVo = new ProductAmountVo();
		productAmountVo.setBusinessType(cartProInfo.getBusinessType());
		productAmountVo.setProSku(proSku);
		productAmountVo.setProductName(cartProInfo.getProName());
		productAmountVo.setPurchasePrice(cartProInfo.getPriorityPrice());
		productAmountVo.setProductNum(proNum.intValue());
		productAmountVo.setSubtotal(ArithUtil.mul(cartProInfo.getPriorityPrice(), proNum, 4));
		productAmountVo.setIsGivePro(ProductAmountVo.IS_GIVE_PRO_NO_0);
		MemberLevel memberLevel = memberAccountService.findByMemberIdAndSysId(memberId, sysId);
		Integer giveJfSum = integralRecordService.getGiveIntegral(productAmountVo.getSubtotal(), memberLevel);
		productAmountVo.setGiveJfSum(giveJfSum);
		result.setData(productAmountVo);
		return result;
	}
	
	@Override
	public List<ProVo> findPro(JSONObject object, Pagination page) {
		// TODO Auto-generated method stub
		return productInfoMapper.findPro(object, page);
	}
	
	@Override
	public ProductInfo getProBySku(String sku) {
		// TODO Auto-generated method stub
		return productInfoMapper.getProBySku(sku);
	}
	
	public ProductInfo selectByProductProSku(String proSku) {
		return productInfoMapper.selectByProductProSku(proSku);
	}
	
	@Override
	public ProductInfo isIntegralPro(String sku) {
		// TODO Auto-generated method stub
		return productInfoMapper.isIntegralPro(sku);
		
	}
	
	@Override
	public BackProductInfoDetailVo findProductInfoDetail(Long proId) {
		// TODO Auto-generated method stub
		return productInfoMapper.findProductInfoDetail(proId);
	}
	
	/**
	 * 后台商品编号查询商品详细信息-添加平台商品时使用
	 * @param proNo
	 * @return
	 */
	@Override
	public Result<BackExtProDetailVo> searchProDetail(Long sysId, String proSku) {
		Result<BackExtProDetailVo> result = new Result<BackExtProDetailVo>();
		// 判断该商品不存在
		ProductInfo productInfo = productInfoMapper.selectByProductProSku(proSku);
		if (productInfo == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setCnMessage("该商品不存在");
			return result;
		}
		// 判断状态为“禁用”
		if (ProductInfo.DISABLE.equals(productInfo.getStatus())) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setCnMessage("该商品己禁用，不可新增");
			return result;
		}
		// 判断该商品己添加，不可重复添加
		JSONObject params = new JSONObject();
		params.put("proId", productInfo.getId());
		params.put("sysId", sysId);
		ProductExtInfo pExtInfo = productExtInfoService.selectByProId(params);
		if (pExtInfo != null) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setCnMessage("该商品己添加，不可重复添加");
			return result;
		}
		// 查询基础信息
		BackExtProDetailVo backExtProDetail = seachProInfoPart(productInfo, sysId, proSku);
		
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setData(backExtProDetail);
		return result;
	}
	
	/**
	 * 后台查询商品通用SKU列表
	 */
	@Override
	public PageResult<List<BackProductInfoVo>> findBackProductInfo(BackProductPlatformSearchVo search, Pagination page) {
		PageResult<List<BackProductInfoVo>> result = new PageResult<List<BackProductInfoVo>>();
		List<BackProductInfoVo> list = productInfoMapper.findBackProductInfo(search, page);
		result.setData(list);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setCnMessage("成功查询");
		result.setTotal_record(page.getTotalRecord());
		return result;
	}
	
	/**
	 * 同步商品使用
	 *
	 * @Title: sendProductInfoToErp 
	 * @author: wuyicheng
	 * @date: 2017年8月11日下午2:50:33 
	 * @param data 数据
	 * @param tag 对应的接口
	 * @return: void
	 * @throws
	 */
	@Override
	public void sendProductInfoToErp(String data, String tag) {
		rocketMQService.doSendSyncMsg(RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_GROUP, //
				RocketMqInfo.SYSTEM_NAME + RocketMqInfo.PRODUCT_NAME, //
				RocketMqInfo.SYSTEM_NAME_ERP, //
				tag, CommonUtils.getUUID(), data);
	}
	
	public BackExtProDetailVo seachProInfoPart(ProductInfo productInfo, Long sysId, String proSku) {
		// 查询基础信息
		BackExtProDetailVo backExtProDetail = productInfoMapper.findExtProDetailByBack(proSku);
		
		// 查询价格信息集合
		List<ProductPriceVo> productPriceVos = productPriceService.findByProductId(sysId, productInfo.getId());
		if (productPriceVos != null && productPriceVos.size() > 0) {
			backExtProDetail.setProductPriceVos(productPriceVos);
		}
		// 查询属性信息集合
		List<BackProInfoPropertyVo> proInfoPropertyVos = productPropertyValueService.seachProInfoProperty(productInfo.getId(), sysId);
		backExtProDetail.setProInfoPropertyVos(proInfoPropertyVos);
		return backExtProDetail;
	}
	
	/***
	 * 
	 * @param proId 商品ID
	 * @param proInfoPrices 价格集合
	 * @param isExchangeInt 是否积分价
	 * @param businessType 商品模式
	 * @throws CustomException
	 */
	@Transactional(rollbackFor = { Exception.class })
	public void insertProPrice(Long proId, List<BackProInfoPrice> proInfoPrices, boolean isExchangeInt, BusinessType businessType, Long updateId) throws CustomException {
		for (BackProInfoPrice backProInfoPrice : proInfoPrices) {
			// 判断联营模式~联营结算价必填
			if (businessType.equals(BusinessType.JOIN_SALES) && backProInfoPrice.getPriceType().equals(BackProInfoPrice.JOINT_SETTLEMENT) && backProInfoPrice.getPrice() == null) {
				throw new CustomException(ErrorCode.PARAM_ABSENT.getCode(), "联营模式~联营结算价必填");
			}
			/*// 判断积分商品和正价商品
			if (isExchangeInt) {
				if ((backProInfoPrice.getPriceType().equals(BackProInfoPrice.INTEGRAL) && backProInfoPrice.getPrice() == null)
						|| (backProInfoPrice.getPriceType().equals(BackProInfoPrice.PLAT) && backProInfoPrice.getPrice() != null)) {
					throw new CustomException(ErrorCode.PARAM_ABSENT.getCode(), "积分兑换商品，积分价格必填，醉品价格不填");
				}
			} else {
				if ((backProInfoPrice.getPriceType().equals(BackProInfoPrice.PLAT) && backProInfoPrice.getPrice() == null)
						|| (backProInfoPrice.getPriceType().equals(BackProInfoPrice.INTEGRAL) && backProInfoPrice.getPrice() != null)) {
					throw new CustomException(ErrorCode.PARAM_ABSENT.getCode(), "正价商品，醉品价格必填，积分价格不填");
				}
			}
			// 判断3个必填价格
			if (backProInfoPrice.getPrice() == null && ((backProInfoPrice.getPriceType().equals(BackProInfoPrice.MARKET))
					|| (backProInfoPrice.getPriceType().equals(BackProInfoPrice.AGENT) && backProInfoPrice.getSysId().equals(BackProInfoPrice.ZUI_PIN)))) {
				throw new CustomException(ErrorCode.PARAM_ABSENT.getCode(), "价格必填");
			}*/
			// 新建价格
			if (backProInfoPrice.getPrice() != null) {
				ProductPrice proPrice = new ProductPrice();
				proPrice.setProId(proId);
				proPrice.setSysId(backProInfoPrice.getSysId());
				proPrice.setPriceType(backProInfoPrice.getPriceType());
				proPrice.setPrice(backProInfoPrice.getPrice());
				proPrice.setUpdateId(updateId);
				productPriceService.insertSelective(proPrice);
			}
		}
	}
	
	/**
	 * 后台查询通用商品详细信息~查看详情使用
	 */
	public Result<BackProductInfoDetailVo> findBackProductInfoDetail(Long proId) {
		Result<BackProductInfoDetailVo> result = new Result<BackProductInfoDetailVo>();
		// 查询基础信息
		BackProductInfoDetailVo productInfoDetail = findProductInfoDetail(proId);
		if (productInfoDetail == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setCnMessage("未查询到通用商品详细信息");
			return result;
		}
		// 属性信息集合
		List<BackProInfoPropertyVo> catProps = productPropertyValueService.seachProInfoProperty(proId, null);
		productInfoDetail.setCatProps(catProps);
		// 价格集合
		List<BackProInfoPrice> backProInfoPrices = productPriceService.findProInfoPrice(proId);
		productInfoDetail.setBackProInfoPrices(backProInfoPrices);
		
		result.setData(productInfoDetail);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setCnMessage("成功查询");
		return result;
	}
	
	/**
	 * 后台新建通用SKU
	 * @throws CustomException 
	 *
	 */
	@Override
	@Transactional(rollbackFor = { Exception.class })
	public Result insertProductInfo(BackProductInfoDetailVo proInfoDetail) throws CustomException {
		Result result = new Result();
		// 判断该商品存在
		ProductInfo parameter = productInfoMapper.selectByProductProSku(proInfoDetail.getProSku());
		if (parameter != null) {
			result.setErrorCode(ErrorCode.OBJECT_EXIST);
			result.setCnMessage("该商品已经存在");
			return result;
		}
		
		ProductInfo productInfo = new ProductInfo();
		BeanUtils.copyProperties(proInfoDetail, productInfo);
		productInfo.setSuppilerId(proInfoDetail.getSupplierId());
		productInfo.setSuppilerName(proInfoDetail.getSupplierName());
		productInfo.setProType(ProductType.PRO.toString());
		productInfo.setBusinessType(proInfoDetail.getBusinessType().toString());
		productInfo.setStatus(ProductInfo.ENABLE);
		productInfo.setCreateTime(DateUtils.getCurrentDateTime());
		productInfo.setUpdateTime(DateUtils.getCurrentDateTime());
		productInfo.setUpdateId(proInfoDetail.getUpdateId());
		productInfo.setCreateId(proInfoDetail.getUpdateId());
		productInfo.setIsVirtual(BackProductInfoDetailVo.YES_VIRTUAL.equals(proInfoDetail.getIsVirtual()));
		productInfo.setErpProId(null);
		// productInfo.setIsExchangeIntegral(proInfoDetail.getIsExchangeIntegral());
		if (proInfoDetail.getProSku() == null) {
			// 86开头的最大SKU 并且加一
			productInfo.setProSku("");
			productInfoMapper.insertSelectiveSpecial(productInfo);
		} else {
			productInfo.setProSku(proInfoDetail.getProSku());
			productInfoMapper.insertSelective(productInfo);
		}
		
		ProductInfo oldProInfo = productInfoMapper.selectByPrimaryKey(productInfo.getId());
		if (oldProInfo == null) {
			throw new CustomException(ErrorCode.ELSE.getCode(), "商品添加失败");
		}
		productInfo.setProSku(oldProInfo.getProSku());
		proInfoDetail.setProSku(oldProInfo.getProSku());
		// 是否积分商品
		boolean isExchangeInt = false;
		if (proInfoDetail.getIsExchangeIntegral().equals(ProductInfo.YES_EXCHANGE_INTEGRAL)) {
			// 积分兑换必须有积分价格
			isExchangeInt = true;
		}
		// 新建品类-通用属性信息集合
		List<BackProInfoPropertyVo> catProps = proInfoDetail.getCatProps();
		if (catProps != null) {
			for (BackProInfoPropertyVo backProInfoPropertyVo : catProps) {
				ProductPropertyValue record = new ProductPropertyValue();
				record.setProId(productInfo.getId());
				record.setPropId(backProInfoPropertyVo.getPropId());
				record.setPropValId(backProInfoPropertyVo.getPropValId());
				record.setPropVal(backProInfoPropertyVo.getPropertyVal());
				record.setUpdateId(proInfoDetail.getUpdateId());
				record.setIsCommon(ProductPropertyValue.YES_COMMON);
				productPropertyValueService.insertSelective(record);
			}
		}
		// 价格
		List<BackProInfoPrice> proInfoPrices = proInfoDetail.getBackProInfoPrices();
		// 新建价格
		insertProPrice(productInfo.getId(), proInfoPrices, isExchangeInt, proInfoDetail.getBusinessType(), proInfoDetail.getUpdateId());
		// 查询联营结算价格
		BigDecimal supplyPrice = productPriceService.findSupplyPrice(productInfo.getId());
		// 同步信息到ERP
		proInfoDetail.setId(productInfo.getId());
		proInfoDetail.setStatus(ProductInfo.ENABLE);
		CategoryInfo ca = categoryInfoService.selectByPrimaryKey(proInfoDetail.getCatId());
		if (ca != null) {
			proInfoDetail.setCatId(ca.getErpCatId());// 将erp分类id仍到erp
		}
		if (supplyPrice != null) {
			syncProductInfo(proInfoDetail, supplyPrice.doubleValue());
		} else {
			syncProductInfo(proInfoDetail, null);
		}
		
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setCnMessage("商品【" + proInfoDetail.getProSku() + "】新建成功！");
		return result;
	}
	
	/**
	 * 修改通用SKU
	 * @throws CustomException 
	 */
	@Transactional(rollbackFor = { Exception.class })
	public Result updateProductInfo(BackProductInfoDetailVo proInfoDetail) throws CustomException {
		Result result = new Result();
		ProductInfo productInfo = new ProductInfo();
		productInfo.setId(proInfoDetail.getId());
		// 判断商品是否被禁用
		ProductInfo oldProductInfo = productInfoMapper.selectById(proInfoDetail.getId());
		if (oldProductInfo == null) {
			result.setErrorCode(ErrorCode.ILLEGAL_PARAM);
			result.setMessage("商品被禁用");
			return result;
		}
		// 判断商品模式是否被修改
		ProductInfo parameter = productInfoMapper.selectById(proInfoDetail.getId());
		// 判断该sku是否有在任何一个平台上架，已经上架了，或者曾经上架过的SKU，以下信息是不可编辑的：商品模式
		List<ProductExtInfo> isExist = productExtInfoService.findExtProByProIdAll(proInfoDetail.getId());
		if (isExist != null && isExist.size() > 0) {
			if (!(parameter.getBusinessType().equals(proInfoDetail.getBusinessType().toString()))) {
				result.setErrorCode(ErrorCode.ILLEGAL_PARAM);
				result.setMessage("该sku有在任何一个平台已经上架了，或者曾经上架过,不可编辑：商品模式");
				return result;
			}
		}
		
		BeanUtils.copyProperties(proInfoDetail, productInfo);
		productInfo.setProType(ProductType.PRO.toString());
		productInfo.setBusinessType(proInfoDetail.getBusinessType().toString());
		productInfo.setSuppilerId(proInfoDetail.getSupplierId());
		productInfo.setSuppilerName(proInfoDetail.getSupplierName());
		if (proInfoDetail.getSupplierCatName() == null) {
			productInfo.setSupplierCatName("");
		}
		productInfo.setUpdateTime(DateUtils.getCurrentDateTime());
		// 如果修改了SKU编码 平台商品也要修改
		if (proInfoDetail.getProSku() != null && !(proInfoDetail.getProSku().equals(parameter.getProSku()))) {
			// 修改该通用商品下的全部平台商品的SKU
			productExtInfoService.updateSkuByProId(proInfoDetail.getId(), proInfoDetail.getProSku());
		}
		productInfoMapper.updateByPrimaryKeySelective(productInfo);
		// 删除属性
		productPropertyValueService.deleteByProId(proInfoDetail.getId());
		// 新增属性
		List<BackProInfoPropertyVo> catProps = proInfoDetail.getCatProps();
		if (catProps != null) {
			for (BackProInfoPropertyVo backProInfoPropertyVo : catProps) {
				ProductPropertyValue record = new ProductPropertyValue();
				record.setProId(productInfo.getId());
				record.setPropId(backProInfoPropertyVo.getPropId());
				record.setPropValId(backProInfoPropertyVo.getPropValId());
				record.setPropVal(backProInfoPropertyVo.getPropertyVal());
				record.setIsCommon(ProductPropertyValue.YES_COMMON);
				productPropertyValueService.insertSelective(record);
			}
		}
		boolean isExchangeInt = false;
		if (proInfoDetail.getIsExchangeIntegral().equals(ProductInfo.YES_EXCHANGE_INTEGRAL)) {
			// 积分兑换必须有积分价格
			isExchangeInt = true;
		}
		// 删除价格
		JSONObject object = new JSONObject();
		object.put("proId", proInfoDetail.getId());
		productPriceService.deleteByProId(object);
		// 修改价格
		List<BackProInfoPrice> proInfoPrices = proInfoDetail.getBackProInfoPrices();
		// 新建价格
		insertProPrice(productInfo.getId(), proInfoPrices, isExchangeInt, proInfoDetail.getBusinessType(), proInfoDetail.getUpdateId());
		// 查询联营结算价格
		BigDecimal supplyPrice = productPriceService.findSupplyPrice(productInfo.getId());
		// 同步信息到ERP
		proInfoDetail.setStatus(oldProductInfo.getStatus());
		proInfoDetail.setErpProId(oldProductInfo.getErpProId());// 将erp的Id传的erp
		CategoryInfo ca = categoryInfoService.selectByPrimaryKey(productInfo.getCatId());
		if (ca != null) {
			proInfoDetail.setCatId(ca.getErpCatId());// 将erp分类id仍到erp
		}
		if (supplyPrice != null) {
			syncProductInfo(proInfoDetail, supplyPrice.doubleValue());
		} else {
			syncProductInfo(proInfoDetail, null);
		}
		
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setMessage("修改成功");
		return result;
	}
	
	/**
	 * 添加体验品
	 * @throws CustomException 
	 */
	/** 
	 * @Title: creatExperiencePro 
	 * @Description: TODO
	 * @author xjd
	 * @param @param experiencePro
	 * @param @param proId
	 * @param @return
	 * @param @throws CustomException
	 * @throws 
	 */
	@Transactional(rollbackFor = { Exception.class })
	public Result creatExperiencePro(BackProductInfoDetailVo experiencePro, Long proId) throws CustomException {
		// 查询通用商品详情BackProductInfoDetailVo proInfo,
		// 查询基础信息
		Result result = new Result();
		BackProductInfoDetailVo proInfo = findProductInfoDetail(proId);
		if (proInfo == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("未查询到通用商品详细信息");
			return result;
		}
		if (proInfo.getProType().equals(ProductType.EXPERIENCE)) {
			result.setErrorCode(ErrorCode.ILLEGAL_PARAM);
			result.setMessage("体验品不可以新建体验品");
			return result;
		}
		// 判断体验品是否可以添加~商品是否是 1正常商品 ，2毛重（净重）不重复，3
		List<ProductInfo> param = productInfoMapper.selectExpProIsRepeat(proInfo.getProSku(), experiencePro.getWeight());
		if (param != null && param.size() > 0) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("该商品编号己存在");
			return result;
		}
		
		experiencePro.setCatId(proInfo.getCatId());//
		experiencePro.setCatProps(proInfo.getCatProps());
		experiencePro.setBrandName(proInfo.getBrandName());
		experiencePro.setIsVirtual(proInfo.getIsVirtual());
		
		// 判断该商品现有体验品个数
		int expProCount = productInfoMapper.findExpProCount(proInfo.getProSku());
		StringBuffer proSku = new StringBuffer();
		proSku.append(proInfo.getProSku());
		proSku.append("-TYP");
		proSku.append(expProCount + 1);
		experiencePro.setProSku(proSku.toString());
		
		// 添加基础信息
		ProductInfo productInfo = new ProductInfo();
		BeanUtils.copyProperties(experiencePro, productInfo);
		productInfo.setProType(ProductType.EXPERIENCE.toString());
		productInfo.setBusinessType(experiencePro.getBusinessType().toString());
		productInfo.setStatus(ProductInfo.ENABLE);
		productInfo.setCreateId(experiencePro.getUpdateId());
		productInfo.setCreateTime(DateUtils.getCurrentDateTime());
		productInfo.setUpdateTime(DateUtils.getCurrentDateTime());
		productInfo.setUpdateId(experiencePro.getUpdateId());
		productInfo.setSuppilerId(experiencePro.getSupplierId());
		productInfo.setSuppilerName(experiencePro.getSupplierName());
		productInfo.setIsVirtual(BackProductInfoDetailVo.YES_VIRTUAL.equals(experiencePro.getIsVirtual()));
		productInfo.setErpProId(null);
		productInfoMapper.insertSelective(productInfo);
		boolean isExchangeInt = false;
		
		if (ProductInfo.YES_EXCHANGE_INTEGRAL.equals(experiencePro.getIsExchangeIntegral())) {
			// 积分兑换必须有积分价格
			isExchangeInt = true;
		}
		// 新建品类-通用属性信息集合(从通用属性拿)
		List<BackProInfoPropertyVo> catProps = productPropertyValueService.seachProInfoProperty(proId, null);
		for (BackProInfoPropertyVo backProInfoPropertyVo : catProps) {
			ProductPropertyValue record = new ProductPropertyValue();
			record.setProId(productInfo.getId());
			record.setPropId(backProInfoPropertyVo.getPropId());
			record.setPropValId(backProInfoPropertyVo.getPropValId());
			record.setPropVal(backProInfoPropertyVo.getPropertyVal());
			record.setIsCommon(ProductPropertyValue.YES_COMMON);
			record.setUpdateId(experiencePro.getUpdateId());
			record.setCreateId(experiencePro.getUpdateId());
			productPropertyValueService.insertSelective(record);
		}
		// 价格
		List<BackProInfoPrice> proInfoPrices = experiencePro.getBackProInfoPrices();
		// 新建价格
		insertProPrice(productInfo.getId(), proInfoPrices, isExchangeInt, experiencePro.getBusinessType(), experiencePro.getUpdateId());
		// 查询联营结算价格
		BigDecimal supplyPrice = productPriceService.findSupplyPrice(productInfo.getId());
		// 同步信息到ERP
		experiencePro.setId(productInfo.getId());
		experiencePro.setStatus(ProductInfo.ENABLE);
		experiencePro.setCatId(proInfo.getErpCatId());// 将erp分类id仍到erp
		if (supplyPrice != null) {
			syncProductInfo(experiencePro, supplyPrice.doubleValue());
		} else {
			syncProductInfo(experiencePro, null);
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setCnMessage("新增成功");
		return result;
		
	}
	
	/**
	 * 修改体验品
	 */
	@Transactional(rollbackFor = { Exception.class })
	public Result updateExperiencePro(BackProductInfoDetailVo experiencePro) throws CustomException {
		// 修改
		Result result = new Result();
		ProductInfo productInfo = new ProductInfo();
		productInfo.setId(experiencePro.getId());
		
		ProductInfo pi = productInfoMapper.findProductInfoById(productInfo.getId());
		if (pi == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setMessage("查无商品");
			return result;
		}
		// 体验品一定是以-TYPXXX结尾 (体验品与其正价商品 唯一关系 ：SKU 加上-TYP) （如果存在体验品不存在-TYP 就报错）
		int idx = pi.getProSku().indexOf("-TYP");
		String proSku = pi.getProSku().substring(0, idx);
		// 判断体验品是否可以修改~商品是否是 1毛重不重复
		List<ProductInfo> param = productInfoMapper.selectExpProIsRepeat(proSku, experiencePro.getWeight());
		if (param != null && param.size() > 0) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("保存失败！该体验品己存在相同毛重产品");
			return result;
		}
		
		experiencePro.setErpProId(pi.getErpProId());
		BeanUtils.copyProperties(experiencePro, productInfo);
		productInfo.setProType(ProductType.EXPERIENCE.toString());
		productInfo.setBusinessType(experiencePro.getBusinessType().toString());
		productInfo.setSuppilerId(experiencePro.getSupplierId());
		productInfo.setSuppilerName(experiencePro.getSupplierName());
		productInfo.setUpdateId(experiencePro.getUpdateId());
		productInfo.setUpdateTime(DateUtils.getCurrentDateTime());
		productInfoMapper.updateByPrimaryKeySelective(productInfo);
		
		boolean isExchangeInt = false;
		if (experiencePro.getIsExchangeIntegral().equals(ProductInfo.YES_EXCHANGE_INTEGRAL)) {
			// 积分兑换必须有积分价格
			isExchangeInt = true;
		}
		// 删除价格
		JSONObject object = new JSONObject();
		object.put("proId", experiencePro.getId());
		productPriceService.deleteByProId(object);
		List<BackProInfoPrice> proInfoPrices = experiencePro.getBackProInfoPrices();
		
		// 新建价格
		insertProPrice(productInfo.getId(), proInfoPrices, isExchangeInt, experiencePro.getBusinessType(), experiencePro.getUpdateId());
		// 查询联营结算价格
		BigDecimal supplyPrice = productPriceService.findSupplyPrice(productInfo.getId());
		// 同步信息到ERP
		experiencePro.setStatus(pi.getStatus());
		CategoryInfo ca = categoryInfoService.selectByPrimaryKey(pi.getCatId());
		if (ca != null) {
			experiencePro.setCatId(ca.getErpCatId());// 将erp分类id仍到erp
		}
		if (supplyPrice != null) {
			syncProductInfo(experiencePro, supplyPrice.doubleValue());
		} else {
			syncProductInfo(experiencePro, null);
		}
		
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setCnMessage("修改成功");
		return result;
	}
	
	/**
	 * 朴茶收银系统查询商品
	 *
	 * @Title: searchProductInfo 
	 * @author: wuyicheng
	 * @date: 2017年8月29日下午4:31:02 
	 * @param sysId 系统ID
	 * @param productSku 商品SKU
	 * @param ignoreProSkus 忽略商品SKU
	 * @param categoryId 分类ID
	 * @param brandId 品牌ID
	 * @param productPriceId 代理商等级对应的价格ID
	 * @param isIgnoreNoPurchasePrice 是否忽略没有代理价的商品
	 * @param pageNumber 页码
	 * @param pageSize 数量
	 * @param sort 排序字段名
	 * @param order 升序降序
	 * @return
	 * @throws CustomException
	 * @throws
	 */
	@Override
	public Result<SearchProductInfoVo> searchProductInfo(Long sysId, String productSku, String ignoreProSkus, Long categoryId, Long brandId, Long productPriceId,
			Short isIgnoreNoPurchasePrice, Integer pageNumber, Integer pageSize, String sort, String order) throws CustomException {
		Result<SearchProductInfoVo> result = new Result<SearchProductInfoVo>();
		SearchProductInfoVo searchProductInfoVo = new SearchProductInfoVo();
		// 获取分类
		List<CategoryInfoVo> categoryInfoVos = categoryInfoService.findRootCategoryInfo(sysId);
		List<Long> categoryIds = null;
		// 不选择全部分类 并且 不选择根目录
		if (categoryId != null && !(categoryId.equals(ConstantsUtil.TREE_ROOT_CODE)) && categoryInfoVos != null && !categoryInfoVos.isEmpty()) {
			categoryIds = new ArrayList<Long>();
			categoryIds.add(categoryId);// 保存当前分类ID
			
			// 是否存在二级分类
			List<CategoryInfoVo> secondCategoryList = categoryInfoVos.get(0).getChildren();
			if (secondCategoryList != null && !secondCategoryList.isEmpty()) {
				// 遍历二级分类是否等于当前选中的分类
				for (CategoryInfoVo secondCcategoryInfoVo : secondCategoryList) {
					if (categoryId.equals(secondCcategoryInfoVo.getId()) && secondCcategoryInfoVo.getChildren() != null) {
						// 三级分类
						List<CategoryInfoVo> thirdCategoryList = secondCcategoryInfoVo.getChildren();
						if (thirdCategoryList != null && !thirdCategoryList.isEmpty()) {
							for (CategoryInfoVo thirdCategoryInfoVo : thirdCategoryList) {
								categoryIds.add(thirdCategoryInfoVo.getId());
							}
						}
						break;
					}
				}
			}
		}
		
		List<Long> brandIds = productInfoMapper.findListByCategotyIds(categoryIds, ProductInfo.ENABLE);
		
		List<ProductBrandVo> productBrandVos = baseProductBrandService.findListByIds(sysId, brandIds);
		
		Pagination page = new Pagination();
		page.setPageNumber(pageNumber);
		page.setPageSize(pageSize);
		
		ProductSearchVo productSearchVo = new ProductSearchVo();
		productSearchVo.setBrandId(brandId);
		productSearchVo.setCatId(categoryId);
		productSearchVo.setProSku(productSku);
		productSearchVo.setSysId(sysId);
		productSearchVo.setStatus(ProductInfo.ENABLE);
		productSearchVo.setState(ProductExtInfo.ON_SHELF);
		productSearchVo.setProductPriceId(productPriceId);
		productSearchVo.setIsIgnoreNoPurchasePrice(isIgnoreNoPurchasePrice);
		productSearchVo.setIsFuzzyQuery(ProductSearchVo.IS_FUZZY_QUERY_YES_1);
		if (StringUtil.isNotBlank(ignoreProSkus)) {
			productSearchVo.setNoProSkus(Arrays.asList(ignoreProSkus.split(",")));
		}
		productSearchVo.setSort(sort);
		productSearchVo.setOrder(order);
		List<ProductCashierVo> productCashierVos = this.findProductByCashier(productSearchVo, page);
		PageInfo<ProductCashierVo> pageInfo = new PageInfo<>(productCashierVos);
		searchProductInfoVo.setProductTotal(pageInfo.getTotal());
		searchProductInfoVo.setCategoryInfoVos(categoryInfoVos);
		searchProductInfoVo.setProductBrandVos(productBrandVos);
		searchProductInfoVo.setProductCashierVos(productCashierVos);
		result.setData(searchProductInfoVo);
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	/**
	 * 收银系统查询商品
	 *
	 * @Title: findProductByCashier 
	 * @author: wuyicheng
	 * @date: 2017年8月21日下午2:58:36 
	 * @param productSearchVo
	 * @param page
	 * @return
	 * @throws CustomException
	 * @return: List<ProductCashierVo>
	 * @throws
	 */
	@Override
	public List<ProductCashierVo> findProductByCashier(ProductSearchVo productSearchVo, Pagination page) throws CustomException {
		String imgPath = zpDomain + zpThumbnail230x184;
		productSearchVo.setImgPath(imgPath);
		if (page != null) {
			PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		}
		List<ProductCashierVo> productCashierVos = productInfoMapper.findProductCashierVo(productSearchVo);
		StringBuffer cartSkus = new StringBuffer();
		if (productCashierVos != null && !productCashierVos.isEmpty()) {
			for (ProductCashierVo productCashierVo : productCashierVos) {
				cartSkus.append(productCashierVo.getProSku()).append(",");
			}
		}
		if (cartSkus != null && cartSkus.length() > 0) {
			// 如果商品库存不够（小于0），则查询出的商品不允许勾选。
			// 如果进货清单已经有商品，再点击选商品，出现的弹窗，不显示原有的商品情况，如果勾选的商品中包含已有的商品，则点击“选好了”把数量加1
			// 如果勾选商品时，有库存，点击“选好了”时没库存，则不添加这个商品，并且做toast提示“商品编号：858382 库存不足”，如果有多个，则显示多个toast
			
			// 检验库存
			Map<String, Map<String, Object>> returnMap = shoppingCartService.findCisBranchStockByProSkus(cartSkus.toString());
			if (productCashierVos != null && !productCashierVos.isEmpty()) {
				for (ProductCashierVo productCashierVo : productCashierVos) {
					// 校验商品库存
					BigDecimal stockNums = (BigDecimal) returnMap.get(productCashierVo.getProSku()).get("validStock");
					// boolean checkStock = shoppingCartService.checkStock(productCashierVo.getProSku(), new BigDecimal(1.00), returnMap);
					productCashierVo.setStockNums(stockNums);
					if (ArithUtil.compareTo(stockNums, new BigDecimal(1.00)) < 0) {
						productCashierVo.setIsSelect(ProductCashierVo.IS_SELECT_NO);
						productCashierVo.setRemark("库存不足");
						// throw new CustomException(ErrorCode.STORAGE_INSUFFICIENT.getCode(), "商品库存不足");
					} else {
						productCashierVo.setIsSelect(ProductCashierVo.IS_SELECT_YES);
					}
				}
			}
		}
		return productCashierVos;
	}
	
	/*
		 * 通用同步信息到ERP
		 * @param ProDetail 
		 * @param supplyPrice 联营结算价
		 * @return
		 */
	@Transactional(rollbackFor = { Exception.class })
	public Result syncProductInfo(BackProductInfoDetailVo proDetail, Double supplyPrice) {
		// 同步信息
		ProductFromCbsVo productFromCbsVo2 = new ProductFromCbsVo();
		productFromCbsVo2.setCbsProId(proDetail.getId());
		productFromCbsVo2.setErpProId(proDetail.getErpProId());
		productFromCbsVo2.setProNo(proDetail.getProSku());
		if (ProductType.PRO.equals(proDetail.getProType())) {
			productFromCbsVo2.setIsExpPro(ProductFromCbsVo.NO_EXPPRO);
		} else {
			productFromCbsVo2.setIsExpPro(ProductFromCbsVo.YES_EXPPRO);
		}
		productFromCbsVo2.setProName(proDetail.getProName());
		if (ProductUnit.件.toString().equals(proDetail.getUnint()) || ProductUnit.箱.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.件_箱);
		} else if (ProductUnit.桶.toString().equals(proDetail.getUnint()) || ProductUnit.条.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.桶_条);
		} else if (ProductUnit.罐.toString().equals(proDetail.getUnint()) || ProductUnit.瓶.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.罐_瓶);
		} else if (ProductUnit.片.toString().equals(proDetail.getUnint()) || ProductUnit.饼.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.片_饼);
		} else if (ProductUnit.克.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.克);
		} else if (ProductUnit.斤.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.斤);
		} else if (ProductUnit.包.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.包);
		} else if (ProductUnit.个.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.个);
		} else if (ProductUnit.台.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.台);
		} else if (ProductUnit.盒.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.盒);
		} else if (ProductUnit.套.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.套);
		} else if (ProductUnit.把.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.把);
		} else if (ProductUnit.次.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.次);
		} else if (ProductUnit.坨.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.坨);
		} else if (ProductUnit.砖.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.砖);
		} else if (ProductUnit.份.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.份);
		} else if (ProductUnit.泡.toString().equals(proDetail.getUnint())) {
			productFromCbsVo2.setProUnit(ProductUnit.泡);
		} else {
			productFromCbsVo2.setProUnit(ProductUnit.其它);
		}
		productFromCbsVo2.setSpecifications(proDetail.getSpecifications());
		if (BackProductInfoDetailVo.YES_VIRTUAL.equals(proDetail.getIsVirtual())) {
			productFromCbsVo2.setIsVirtual(ProductFromCbsVo.YES_VIRTUAL);
		} else {
			productFromCbsVo2.setIsVirtual(ProductFromCbsVo.NO_VIRTUAL);
		}
		productFromCbsVo2.setProductCatId(proDetail.getCatId());
		productFromCbsVo2.setProductType(proDetail.getBusinessType() == null ? 0 : proDetail.getBusinessType().getKey());
		productFromCbsVo2.setStatus(ProductStatus.changeToErpStatus(proDetail.getStatus()));
		
		productFromCbsVo2.setSupplyPrice(supplyPrice);
		productFromCbsVo2.setSupplierId(proDetail.getSupplierId());
		productFromCbsVo2.setSupplierUseName(proDetail.getSupplierCatName());
		productFromCbsVo2.setWeight(proDetail.getWeight().doubleValue());
		// 查询修改人信息
		SysUser sysUser = sysUserService.findById(proDetail.getUpdateId());
		if (sysUser != null) {
			productFromCbsVo2.setUpator(sysUser.getRealName());
		}
		productFromCbsVo2.setUpdateTime(DateUtils.getCurrentDateTime());
		productFromCbsVo2.setProNoSku(proDetail.getProNo());
		// 将信息放入list
		List<ProductFromCbsVo> list = new ArrayList<ProductFromCbsVo>();
		list.add(productFromCbsVo2);
		
		sendProductInfoToErp(com.alibaba.fastjson.JSONObject.toJSON(list).toString(), RocketMQTagEnum.TO_SYNC_PEODUCT_FROM_CBS.toString());
		
		return null;
	}
	
	/**
	 * 
	 * @Title: updateProductErpId 
	 * @Description: 修改商品中erpId
	 * @author xjd
	 * @param 
	 * @return void
	 * @throws
	 */
	// {[{cbsProId:1,erpProId:2},{}]}
	public void updateProductErpId(RocketMqInfo mqInfo) {
		if (mqInfo != null && !StringUtil.isBlank(mqInfo.getBody())) {
			JSONObject obj = JSONObject.fromObject(mqInfo.getBody());
			long cbsProId = obj.getLong("cbsProId");
			long erpProId = obj.getLong("erpProId");
			ProductInfo pi = new ProductInfo();
			pi.setId(cbsProId);
			pi.setErpProId(erpProId);
			// 修改人和时间不保存
			productInfoMapper.updateByPrimaryKeySelective(pi);
		}
	}
}
